import torch
from numpy.matrixlib.defmatrix import matrix

if __name__ == '__main__':
    # 1. 创建张量
    print(torch.tensor([1, 2, 3]))
    # 创建全零张量
    zeros = torch.zeros(2,3)
    print(zeros)
    # 创建全一张量
    ones = torch.ones(2,3)
    print(ones)
    # 创建随机张量
    range_tensor =  torch.rand(2,3)
    print(range_tensor)
    # 运算
    a = torch.tensor([1,2,3])
    b = torch.tensor([4,5,6])
    add_res = a + b
    print(add_res)
    print(a * b)
    # 矩阵乘法
    matrix_a = torch.randn(2,3)
    print(matrix_a)
    matrix_b = torch.randn(3,2)
    print(matrix_b)
    print(torch.matmul(matrix_a, matrix_b))
    # 0 维张量：标量（如 3.14，无维度）
    # 1 维张量：向量（如 [1, 2, 3]，形状 (3,)）
    # 2 维张量：矩阵（如上面的 2 行 3 列数组，形状 (2, 3)）
    # 3 维张量：如 [[[1,2], [3,4]], [[5,6], [7,8]]]（形状 (2, 2, 2)）
    tensor = torch.rand(4, 3)
    print(f"原始形状: {tensor.shape}")
    reshaped = tensor.reshape(2, 6)
    print(f"重塑后: {reshaped.shape}")
    transposed = tensor.T
    print(f"转置后: {transposed.shape}")
    # 4. 与NumPy互操作
    print("\n=== 与NumPy互操作 ===")
    import numpy as np

    numpy_array = np.array([1, 2, 3])
    tensor_from_numpy = torch.from_numpy(numpy_array)
    print(f"从NumPy创建: {tensor_from_numpy}")
    # 从PyTorch张量创建NumPy数组
    tensor = torch.tensor([4, 5, 6])
    numpy_from_tensor = tensor.numpy()
    print(f"转换为NumPy: {numpy_from_tensor}")